import java.util.*;
import java.io.*;

public class NotePad {
    static Scanner in = new Scanner(System.in);
	public static void main(String[] args) throws Exception{
		//创建死循环，让程序一直执行下去
		while(true){
			
			//提示用户操作
			System.out.println("请输入你要进行的操作");
			System.out.println("1=读取记事本，2=创建记事本，0=退出程序");
			int i = in.nextInt();
			
			//实现功能选择
			if( i == 1 ){
				//调用Reader方法进行读取操作
				Reader.read();
			}else if( i == 2 ){
				//调用Write方法进行创建文件
				Write.write();
			}else if( i == 0 ){
				//程序退出
				break;
			}else{
				System.out.println("请选择正确的操作");
			}
		}
	}
}

//创建读取类
class Reader{
	static Scanner in = new Scanner(System.in);
	
	public static void read() throws Exception{
		System.out.println("请输入你要查看的文件名的路径：");
		String filename = in.next();
		File readfile = new File(filename);
		
		//判断文件是否存在，如果文件不存在就询问用户是否创建
		if( readfile.exists() == false ){
			
			System.out.println("没有找到该文件，是否创建？y/n");
			String yn = in.next();
			
			if( yn.equals("y") ){
					//调用write方法进行创建
					Write.write();
			}
		}
		
		//如果文件存在，直接读取
		FileInputStream fis = new FileInputStream(filename);
		InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
		BufferedReader br = new BufferedReader(isr);
		
		String line;
		System.out.println("");
		while( (line = br.readLine() ) != null ){
			System.out.println("记事本内容为:\n  "+line);
		}	
		System.out.println("");
		
		br.close();
		isr.close();
		fis.close();
	}
}

class Write{
	static Scanner in = new Scanner(System.in);
	
	public  static void write() throws Exception{		
		System.out.println("请输入你要创建的文件名：");
		String wriname = in.next();
		
		FileOutputStream fos = new FileOutputStream(wriname);
		OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
		BufferedWriter bw = new BufferedWriter(osw);
		
		File file = new File(wriname);
		//判断文件是否创建成功，如果创建成功，则输入数据,如果创建失败，则提示用户是否再次创建
		if( file.exists() == false ){
			System.err.println("文件创建失败！");
			System.out.println("是否重新创建？y/n");
			String s = in.next();
			if( s.equals("y") ){
				Write.write();
			}
		}		
		System.out.println("(请使用转义字符)正在输入：");
		
		String strWrite = in.next();
		bw.write(strWrite);
		
		bw.close();
		osw.close();
		fos.close();
		
		//询问用户是否查看文件
		System.out.println("是否查看文件? y/n");
		String s = in.next();
		if( s.equals("y") ){
			Reader.read();
		}
	}
}